///
///  This source code is freeware and is provided on an "as is" basis without warranties of any kind, 
///  whether express or implied, including without limitation warranties that the code is free of defect, 
///  fit for a particular purpose or non-infringing.  The entire risk as to the quality and performance of 
///  the code is with the end user.
///
using System;
using System.Web;
using System.Text;
using System.IO;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using System.Configuration;
namespace Samples
{
    /// <summary>
    /// This module allows to protect only certain areas of a Sharepoint site
    /// </summary>
    [AspNetHostingPermission(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal), SharePointPermission(SecurityAction.InheritanceDemand, ObjectModel = true), AspNetHostingPermission(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal), SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]
    public class SharePointSSLHttpModule : IHttpModule
    {
        private HttpApplication mApplication;
        private String baseURLNoSSL;
        private String baseURLWithSSL;
        const String BASEURL_NOSSL = "BASEURL_NOSSL";
        const String BASEURL_SSL = "BASEURL_SSL";

        public void Init(System.Web.HttpApplication application)
        {
            // Wire up PreRequestHandler
            application.PreRequestHandlerExecute += new EventHandler(PreRequest);
            // Save the application
            mApplication = application;
            if (ConfigurationManager.AppSettings[BASEURL_NOSSL] != null)
            {
                baseURLNoSSL = System.Configuration.ConfigurationManager.AppSettings[BASEURL_NOSSL];
            }
            if (ConfigurationManager.AppSettings[BASEURL_SSL] != null)
            {
                baseURLWithSSL = System.Configuration.ConfigurationManager.AppSettings[BASEURL_SSL];
            }

        }

        public void PreRequest(object sender, EventArgs e)
        {
            HttpContext ctx = null;
			SPContext spContext = null;
			// try-catch to prevent access denied exception during forms login.
			try
			{
                ctx = HttpContext.Current;
                spContext = SPContext.Current;
                if (spContext != null)
                {
                    if (spContext.Web != null)
                    {
                        bool RequireSSL = false;
                        if (spContext.Web.Properties.ContainsKey("requiressl"))
                        {
                            
                            RequireSSL = (spContext.Web.Properties["requiressl"].ToString()).ToLower() == "yes";
                        }
                            string PathAndQuery = ctx.Request.Url.PathAndQuery;
                            if (PathAndQuery.ToLower().Contains("_layouts")) return;
                            
                        


                        if (RequireSSL & !ctx.Request.IsSecureConnection)
                        {
                            if (baseURLWithSSL!=null)
                                ctx.Response.Redirect(baseURLWithSSL + PathAndQuery);
                            else
                                ctx.Response.Redirect("https://" + ctx.Request.Url.Host + PathAndQuery);
                            return;
                        }
                        if (!RequireSSL & ctx.Request.IsSecureConnection)
                        {
                            if (baseURLNoSSL!=null)
                                ctx.Response.Redirect(baseURLNoSSL + PathAndQuery);
                            else
                                ctx.Response.Redirect("http://" + ctx.Request.Url.Host + PathAndQuery);
                            return;
                        }
                        
                    }
                }

			}
			catch
			{
				// nothing to do...
			}

		}

       public void Dispose() {}

    }
}